<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- <el-form-item label="优先级" prop="priority">
        <el-input
          v-model="queryParams.priority"
          placeholder="请输入优先级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="标签名称" prop="tagName">
        <el-input
          v-model="queryParams.tagName"
          placeholder="请输入标签名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标签字段" prop="tagField">
        <el-input
          v-model="queryParams.tagField"
          placeholder="请输入标签字段"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据表名" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入数据表名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="策略数量" prop="strategyCount">
        <el-input
          v-model="queryParams.strategyCount"
          placeholder="请输入策略数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否激活" prop="isActive">
        <el-input
          v-model="queryParams.isActive"
          placeholder="请输入是否激活"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker clearable
          v-model="queryParams.createdAt"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" prop="updatedAt">
        <el-date-picker clearable
          v-model="queryParams.updatedAt"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['conf:biruletag:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['conf:biruletag:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['conf:biruletag:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['conf:biruletag:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button size="mini" @click="openvariable = true">
          配置变量
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button size="mini" @click="handleRuleTagger">打标</el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table :data="biruletagList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="自增ID" align="center" prop="id" /> -->
      <el-table-column label="优先级" align="center" prop="priority" />

      <el-table-column label="标签字段" align="center" prop="tagField" />
      <el-table-column label="标签类型" align="center" prop="tagType">
        <template slot-scope="scope">
          {{ scope.row.tagType | state1 }}
        </template>
      </el-table-column>

      <el-table-column label="标签名称" align="center" prop="tagName">
        <template slot-scope="scope">
          <span v-if="scope.row.tagType == 'define'">{{
            scope.row.tagName
          }}</span>
          <span
            v-if="scope.row.tagType != 'define'"
            style="
              color: rgb(37, 137, 255);
              cursor: pointer;
              text-decoration: underline;
              font-weight: bold;
            "
            @click="gotoApply(scope.row)"
            >{{ scope.row.tagName }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="数据表名" align="center" prop="tableName" />
      <el-table-column label="策略数量" align="center" prop="strategyCount" />
      <el-table-column label="策略匹配逻辑" align="center" prop="matchLogic" />
      <el-table-column label="是否激活" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isActive"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="条件设置" align="center">
        <template slot-scope="scope">
          <span
            style="
              color: rgb(37, 137, 255);
              cursor: pointer;
              text-decoration: underline;
              font-weight: bold;
            "
            @click="tableEdit(scope.row)"
            >条件设置</span
          >
        </template>
      </el-table-column>
      <!-- <el-table-column label="标签备注" align="center" prop="remark" /> -->
      <!-- <el-table-column
        label="创建时间"
        align="center"
        prop="createdAt"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updatedAt"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['conf:biruletag:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['conf:biruletag:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog
      :visible.sync="openRule"
      width="90%"
      append-to-body
      v-if="openRule"
    >
      <BiRuleSpecifications
        :id="id"
        :tableName="queryParams.tableName"
        :biruletagList="biruletagList"
      />
    </el-dialog>
    <!-- 添加或修改BI标签一级配置表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="优先级" prop="priority">
          <!-- <el-input v-model="form.priority" placeholder="请输入优先级" /> -->
          <el-select
            v-model="form.priority"
            placeholder="请输入优先级"
            clearable
            filterable
          >
            <el-option
              v-for="dict in 10"
              :key="dict"
              :label="dict"
              :value="dict"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="标签字段" prop="tagField">
          <el-select
            v-model="form.tagField"
            placeholder="请输入打标字段"
            clearable
            filterable
          >
            <el-option
              v-for="dict in tagNameList"
              :key="dict.field_name"
              :label="dict.comment"
              :value="dict.field_name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" prop="tagName">
          <!-- -->

          <el-select
            v-model="form.tagType"
            style="width: 120px"
            @change="changecompareValue"
          >
            <el-option label="自定义" value="define" />
            <el-option label="从变量选" value="variable" />
            <el-option label="表关联" value="tableRelation" />
          </el-select>
          <el-input
            v-show="form.tagType == 'define'"
            style="width: 200px"
            v-model="form.tagName"
            placeholder="请输入标签名称"
          />
          <!-- @blur="validateInput(form.tagName)" -->
          <el-select
            v-show="form.tagType == 'variable'"
            v-model="form.tagName"
            placeholder="请输入标签名称"
            clearable
            filterable
          >
            <el-option
              v-for="dict in variableNameList"
              :key="dict.field_name"
              :label="dict.comment"
              :value="dict.field_name"
            />
          </el-select>
          <el-select
            v-show="form.tagType == 'tableRelation'"
            v-model="form.tagName"
            placeholder="请输入表关系描述"
            clearable
            filterable
            @focus="selectCalulatorTableRelationList"
          >
            <el-option
              v-for="dict in CalulatorTableRelationList"
              :key="dict.id"
              :label="dict.relationshipDescription"
              :value="dict.id"
            />
          </el-select>
          <el-button
            @click="openvariable = true"
            v-show="form.tagType != 'tableRelation'"
          >
            +
          </el-button>
          <el-button
            @click="openInfo = true"
            v-show="form.tagType == 'tableRelation'"
          >
            +
          </el-button>
        </el-form-item>
        <el-form-item label="匹配模式" prop="matchLogic">
          <!-- <el-input v-model="form.matchLogic" placeholder="请输入匹配模式" /> -->
          <el-select
            v-model="form.matchLogic"
            placeholder="请输入匹配模式"
            clearable
            filterable
          >
            <el-option
              v-for="dict in matchLogicList"
              :key="dict"
              :label="dict"
              :value="dict"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="标签备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入标签备注" />
        </el-form-item> -->
        <!-- <el-form-item label="策略数量" prop="strategyCount">
          <el-input v-model="form.strategyCount" placeholder="请输入策略数量" />
        </el-form-item>
        <el-form-item label="是否激活" prop="isActive">
          <el-input v-model="form.isActive" placeholder="请输入是否激活" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker
            clearable
            v-model="form.createdAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedAt">
          <el-date-picker
            clearable
            v-model="form.updatedAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择更新时间"
          >
          </el-date-picker>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="openvariable"
      width="90%"
      append-to-body
      v-if="openvariable"
      @close="handleClosed"
    >
      <BiCalculatorVariables
        :applicationTable="tableName"
        :querytagName="querytagName"
      ></BiCalculatorVariables>
    </el-dialog>

    <el-dialog
      :visible.sync="openInfo"
      width="90%"
      append-to-body
      v-if="openInfo"
    >
      <CalulatorTableRelation
        :querytagName="querytagName"
      ></CalulatorTableRelation>
    </el-dialog>
    <!-- 
      @close="handleClosed"
      :applicationTable="tableName"
        :querytagName="querytagName" -->
  </div>
</template>

<script>
import {
  listBiCalculatorVariables,
  getBiCalculatorVariables,
  delBiCalculatorVariables,
  addBiCalculatorVariables,
  updateBiCalculatorVariables,
  variableList,
} from "@/api/conf/BiCalculatorVariables";
import BiRuleSpecifications from "@/views/conf/BiRuleSpecifications/index.vue";
import BiCalculatorVariables from "@/views/conf/BiCalculatorVariables/edit.vue";
import {
  listBiruletag,
  getBiruletag,
  delBiruletag,
  addBiruletag,
  updateBiruletag,
  activeRule,
} from "@/api/conf/biruletag";
import {
  listBiRuleSpecifications,
  getBiRuleSpecifications,
  delBiRuleSpecifications,
  addBiRuleSpecifications,
  updateBiRuleSpecifications,
  RuleTagger,
  getTablefieldsWithComments,
} from "@/api/conf/BiRuleSpecifications";
import {
  listCalulatorTableRelation,
  getCalulatorTableRelation,
  delCalulatorTableRelation,
  addCalulatorTableRelation,
  updateCalulatorTableRelation,
} from "@/api/conf/CalulatorTableRelation";
import CalulatorTableRelation from "@/views/conf/CalulatorTableRelation/index.vue";

export default {
  components: {
    BiRuleSpecifications,
    BiCalculatorVariables,
    CalulatorTableRelation,
  },
  props: {
    sqlTableName: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      openRule: false,
      CalulatorTableRelationList: [],
      openInfo: false,
      querytagName: "",
      openvariable: false,
      tagName: "input",
      opentagName: false,
      variableNameList: [],
      matchLogicList: ["ANY", "ALL"],
      id: 0,
      tableName: "",
      tagNameList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // BI标签一级配置表表格数据
      biruletagList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        priority: null,
        tagName: null,
        tagField: null,
        tableName: "",
        strategyCount: null,
        matchLogic: null,
        isActive: null,
        createdAt: null,
        updatedAt: null,
      },
      // 表单参数
      form: {
        tagType: "define",
      },
      // 表单校验
      rules: {
        priority: [
          { required: true, message: "优先级不能为空", trigger: "blur" },
        ],
        tagName: [
          { required: true, message: "标签名称不能为空", trigger: "blur" },
        ],
        tagField: [
          { required: true, message: "标签字段不能为空", trigger: "blur" },
        ],
        tableName: [
          { required: true, message: "数据表名不能为空", trigger: "blur" },
        ],
        matchLogic: [
          { required: true, message: "策略匹配逻辑不能为空", trigger: "blur" },
        ],
        isActive: [
          { required: true, message: "是否激活不能为空", trigger: "blur" },
        ],
        createdAt: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
        updatedAt: [
          { required: true, message: "更新时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  filters: {
    state1(string) {
      if (string == "variable") {
        return "变量";
      }
      if (string == "define") {
        return "自定义";
      }
      if (string == "tableRelation") {
        return "表关系";
      }
      // if (int == 2) { return "审批通过" };
    },
  },
  watch: {
    // "queryParams.tableName": {
    //   handler(newVal, oldVal) {
    //     console.log(newVal);
    //     if (!this.queryParams.tableName) {
    //       return;
    //     }
    //     this.queryParams.tableName = this.queryParams.tableName;
    //     // this.selectgetTablefieldsWithComments();
    //   },
    // },
    sqlTableName: {
      handler: function (newnew, oldold) {
        this.queryParams.tableName = this.sqlTableName;
        this.getList();
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    // if (this.$route.query.tableName) {
    //   this.queryParams.tableName = this.$route.query.tableName;
    // }
    // this.getList();
    // //
  },
  methods: {
    selectCalulatorTableRelationList() {
      let obj = {
        pageNum: 1,
        pageSize: 1000,
      };
      listCalulatorTableRelation(obj).then((response) => {
        this.CalulatorTableRelationList = response.rows;
      });
    },
    // 打开加载层
    openLoading() {
      this.$modal.loading("正在加载，请稍候！");
    },
    handleRuleTagger() {
      this.openLoading();
      RuleTagger({ tableName: this.queryParams.tableName }).then((response) => {
        this.$modal.closeLoading();
        if (response.code == 200) {
          this.$modal.msgSuccess("打标成功");
          this.getList();
        }
      });
    },
    gotoApply(row) {
      this.tableName = row.tableName;
      this.querytagName = row.tagName;
      if (row.tagType == "variable") {
        this.openvariable = true;
      }
      if (row.tagType == "tableRelation") {
        this.openInfo = true;
      }
    },

    handleClosed() {
      this.getlistBiCalculatorVariables();
    },
    // handleString(key) {
    //   console.log(key);
    // },
    validateInput(value) {
      // 使用正则表达式检查输入是否为纯数字
      if (/^\d+$/.test(value)) {
        this.$modal.msgError("不允许纯数字");
        value = "";
      }
    },
    changecompareValue(tagName) {
      if (tagName == "variable") {
        this.getlistBiCalculatorVariables();
      } else if (tagName == "define") {
        this.form.tagName = "";
      }
    },
    selectgetTablefieldsWithComments() {
      if (!this.queryParams.tableName) {
        return;
      }
      getTablefieldsWithComments({
        tableName: this.queryParams.tableName,
      }).then((response) => {
        this.tagNameList = [];
        response.forEach((element) => {
          // if (element.comment.includes("标签")) {
          this.tagNameList.push(element);
          // }
        });
      });
    },
    tableEdit(row, column, cell, event) {
      this.id = row.id;
      this.openRule = true;
    },
    /** 查询BI标签一级配置表列表 */
    getList() {
      this.loading = true;
      listBiruletag(this.queryParams).then((response) => {
        this.biruletagList = response.rows ? response.rows : [];
        this.total = response.total;
        if (this.biruletagList.length > 0) {
          this.id = response.rows[0].id;
        }

        this.loading = false;
        this.getlistBiCalculatorVariables();
      });
    },
    getlistBiCalculatorVariables() {
      variableList({
        applicationTable: this.queryParams.tableName,
      }).then((response) => {
        let row = [];
        response.forEach((element) => {
          row.push({
            comment: element.variableName,
            field_name: element.id,
          });
        });
        this.variableNameList = row;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        priority: null,
        tagName: null,
        tagField: null,
        tableName: null,
        strategyCount: null,
        matchLogic: null,
        isActive: null,
        createdAt: null,
        updatedAt: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {};
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加BI标签一级配置表";
      this.selectgetTablefieldsWithComments();
      this.selectCalulatorTableRelationList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBiruletag(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改BI标签一级配置表";
        this.selectgetTablefieldsWithComments();
        this.selectCalulatorTableRelationList();
      });
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.isActive === "0" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '"规则吗？')
        .then(function () {
          return activeRule({
            id: row.id,
            isActive: row.isActive,
          });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.isActive = row.isActive === "0" ? "1" : "0";
        });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.tableName = this.queryParams.tableName;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBiruletag(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBiruletag(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除BI标签一级配置表编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBiruletag(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "conf/biruletag/export",
        {
          ...this.queryParams,
        },
        `biruletag_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
